package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private  MovementApi MovementApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private CommentApi commentApi;

    /**
     * 查询用户列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        List<UserInfo> list = iPage.getRecords();
        for (UserInfo userInfo : list) {
            String key = Constants.USER_FREEZE + userInfo.getId();
            if (redisTemplate.hasKey(key)){
                userInfo.setUserStatus("2");
            }

        }
        return new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());

    }

    /**
     * 根据用户ID查询用户详情
     *
     * @param userId
     * @return
     */
    public UserInfo findUserById(Long userId) {

        UserInfo userInfo = userInfoApi.findById(userId);
        //在Redis中查询冻结状态
        String key = Constants.USER_FREEZE + userId;
        if (redisTemplate.hasKey(key)){
            userInfo.setUserStatus("2");
        }

        return userInfo;
    }

    /**
     * 查询指定用户发布的所有视频列表
     *
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }

    /**
     * 查询动态列表
     *
     * @param page
     * @param pagesize
     * @param uid
     * @param status
     * @return
     */
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer status) {
        //1、调用API查询数据 ：Movment对象
        PageResult result = movementApi.findByUserId(uid, status, page, pagesize);
        //2、解析PageResult，获取Movment对象列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3、一个Movment对象转化为一个Vo
        if (CollUtil.isEmpty(items)){
            return new PageResult();
        }
        //获取动态的所有用户ID
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        //通过userIds 获取所有的用户
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId()); //通过单个动态知道单个用户ID，再得到用户详情
            if (userInfo != null){
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                vos.add(vo);
            }
        }
        //4、构造返回值
        result.setItems(vos);
        return result;
    }

    /**
     * 用户冻结
     * @param params
     * @return
     */
    public Map userFreeze(Map params) {
        //1、构造key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //2、构造失效时间
        Integer freezingTime = Integer.valueOf(params.get("freezingTime").toString());//冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
        int days = freezingTime == 1 ? 3 :(freezingTime == 2 ? 7 :0);
        //3、将数据存入Redis
        String value = JSON.toJSONString(params);
        if (days >0) {
            redisTemplate.opsForValue().set(key,value,days, TimeUnit.MINUTES);
        }else {
            redisTemplate.opsForValue().set(key,value);
        }
       Map remap = new HashMap();
        remap.put("message","冻结成功");
        return remap;
    }

    /**
     * 用户解冻
     * @param params
     * @return
     */
    public Map userUnfreeze(Map params) {
        //1、构造key
        String userId = params.get("userId").toString();
        String key = Constants.USER_FREEZE + userId;
        //删除Redis
        redisTemplate.delete(key);
        Map remap = new HashMap();
        remap.put("message","恭喜你解封成功");
        return remap;


    }

    /**
     * 获取用户动态详情
     * @param movementId
     * @return
     */
    public ResponseEntity findMovementById(String movementId) {
        Movement movement = movementApi.findById(movementId);

        UserInfo userInfo = userInfoApi.findById(movement.getUserId());

        MovementsVo vo = MovementsVo.init(userInfo,movement);

        return ResponseEntity.ok(vo);

    }
    /**
     * 分页查询评论列表
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        //1、调用API查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0L, vos);
    }


}


